<template>
  <div class="admin-majors">
    <!-- 头部工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新增专业
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedItems.length">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="院校">
          <el-select v-model="searchForm.schoolId" placeholder="选择院校" clearable>
            <el-option 
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入专业名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="专业分类">
          <el-select v-model="searchForm.category" placeholder="选择专业分类" clearable>
            <el-option 
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadMajors">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="tableData" 
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="专业名称" />
      <el-table-column prop="code" label="专业代码" />
      <el-table-column prop="category" label="专业分类" />
      <el-table-column prop="schoolName" label="所属院校" />
      <el-table-column prop="studyYears" label="学制(年)" width="80" />
      <el-table-column prop="tuitionFee" label="学费" width="100">
        <template #default="scope">
          <span v-if="scope.row.tuitionFee">¥{{ scope.row.tuitionFee }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" class="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadMajors"
        @current-change="loadMajors"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="院校" prop="schoolId">
          <el-select v-model="formData.schoolId" placeholder="选择院校">
            <el-option 
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入专业名称" />
        </el-form-item>
        <el-form-item label="专业代码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入专业代码" />
        </el-form-item>
        <el-form-item label="专业分类" prop="category">
          <el-input v-model="formData.category" placeholder="请输入专业分类" />
        </el-form-item>
        <el-form-item label="学制" prop="studyYears">
          <el-input-number v-model="formData.studyYears" :min="1" :max="6" />
        </el-form-item>
        <el-form-item label="学费">
          <el-input-number v-model="formData.tuitionFee" :min="0" :step="100" />
        </el-form-item>
        <el-form-item label="专业描述">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入专业描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch 
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog 
      title="专业详情"
      v-model="detailDialogVisible"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="专业名称">{{ currentMajor.name }}</el-descriptions-item>
        <el-descriptions-item label="专业代码">{{ currentMajor.code }}</el-descriptions-item>
        <el-descriptions-item label="专业分类">{{ currentMajor.category }}</el-descriptions-item>
        <el-descriptions-item label="所属院校">{{ currentMajor.schoolName }}</el-descriptions-item>
        <el-descriptions-item label="学制">{{ currentMajor.studyYears }}年</el-descriptions-item>
        <el-descriptions-item label="学费">
          <span v-if="currentMajor.tuitionFee">¥{{ currentMajor.tuitionFee }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">
          <el-tag :type="currentMajor.status === 1 ? 'success' : 'danger'">
            {{ currentMajor.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="专业描述" :span="2">
          {{ currentMajor.description || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDateTime(currentMajor.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { getMajorPage, createMajor, updateMajor, deleteMajor, deleteMajorBatch, getCategories } from '@/api/major'
import { getSchools } from '@/api/school'

export default {
  name: 'AdminMajors',
  components: {
    Plus,
    Delete
  },
  setup() {
    const loading = ref(false)
    const tableData = ref([])
    const selectedItems = ref([])
    const schools = ref([])
    const categories = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      schoolId: null,
      name: '',
      category: ''
    })

    // 分页
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 对话框
    const dialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)
    const currentMajor = ref({})
    
    // 表单
    const formRef = ref(null)
    const formData = reactive({
      schoolId: null,
      name: '',
      code: '',
      category: '',
      studyYears: 3,
      tuitionFee: null,
      description: '',
      status: 1
    })

    const formRules = {
      schoolId: [{ required: true, message: '请选择院校', trigger: 'change' }],
      name: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
      code: [{ required: true, message: '请输入专业代码', trigger: 'blur' }],
      category: [{ required: true, message: '请输入专业分类', trigger: 'blur' }]
    }

    // 加载院校列表
    const loadSchools = async () => {
      try {
        const response = await getSchools()
        schools.value = response.data || []
      } catch (error) {
        console.error('加载院校列表失败:', error)
      }
    }

    // 加载专业分类
    const loadCategories = async () => {
      try {
        const response = await getCategories()
        categories.value = response.data || []
      } catch (error) {
        console.error('加载专业分类失败:', error)
      }
    }

    // 加载专业列表
    const loadMajors = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          size: pagination.size,
          ...searchForm
        }
        
        const response = await getMajorPage(params)
        const data = response.data
        
        tableData.value = data.records || []
        pagination.total = data.total || 0
        
        // 设置院校名称
        tableData.value.forEach(major => {
          const school = schools.value.find(s => s.id === major.schoolId)
          major.schoolName = school ? school.name : ''
        })
      } catch (error) {
        console.error('加载专业列表失败:', error)
        ElMessage.error('加载专业列表失败')
      } finally {
        loading.value = false
      }
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        schoolId: null,
        name: '',
        category: ''
      })
      pagination.page = 1
      loadMajors()
    }

    // 显示新增对话框
    const showCreateDialog = () => {
      dialogTitle.value = '新增专业'
      isEdit.value = false
      dialogVisible.value = true
      resetForm()
    }

    // 编辑
    const handleEdit = (row) => {
      dialogTitle.value = '编辑专业'
      isEdit.value = true
      dialogVisible.value = true
      Object.assign(formData, row)
    }

    // 查看详情
    const handleView = (row) => {
      currentMajor.value = { ...row }
      const school = schools.value.find(s => s.id === row.schoolId)
      currentMajor.value.schoolName = school ? school.name : ''
      detailDialogVisible.value = true
    }

    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除专业"${row.name}"吗？`,
          '确认删除',
          { type: 'warning' }
        )
        
        await deleteMajor(row.id)
        ElMessage.success('删除成功')
        loadMajors()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 批量删除
    const handleBatchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的${selectedItems.value.length}个专业吗？`,
          '确认删除',
          { type: 'warning' }
        )
        
        const ids = selectedItems.value.map(item => item.id)
        await deleteMajorBatch(ids)
        ElMessage.success('批量删除成功')
        loadMajors()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    }

    // 选择变更
    const handleSelectionChange = (selection) => {
      selectedItems.value = selection
    }

    // 保存
    const handleSave = async () => {
      try {
        await formRef.value.validate()
        
        if (isEdit.value) {
          await updateMajor(formData.id, formData)
          ElMessage.success('更新成功')
        } else {
          await createMajor(formData)
          ElMessage.success('创建成功')
        }
        
        dialogVisible.value = false
        loadMajors()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(formData, {
        schoolId: null,
        name: '',
        code: '',
        category: '',
        studyYears: 3,
        tuitionFee: null,
        description: '',
        status: 1
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString()
    }

    onMounted(() => {
      loadSchools()
      loadCategories()
      loadMajors()
    })

    return {
      loading,
      tableData,
      selectedItems,
      schools,
      categories,
      searchForm,
      pagination,
      dialogVisible,
      detailDialogVisible,
      dialogTitle,
      isEdit,
      currentMajor,
      formRef,
      formData,
      formRules,
      loadMajors,
      resetSearch,
      showCreateDialog,
      handleEdit,
      handleView,
      handleDelete,
      handleBatchDelete,
      handleSelectionChange,
      handleSave,
      resetForm,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.admin-majors {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.search-form {
  background: #f5f5f5;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.danger {
  color: #f56c6c;
}
</style>